﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace CodePlex.Resourceful
{

    public class PostBodyWriter : IDisposable
    {
        private readonly BinaryWriter _writer;
        private readonly string _boundary;
        private readonly string _newline;

        public PostBodyWriter(BinaryWriter writer, NameValuePairs headers)
        {
            _writer = writer;
            _boundary = "7d44e178b0434";    // TODO

            headers[HttpHeader.ContentType] = string.Format("multipart/form-data; boundary=---------------------------{0}", _boundary);

            _newline = "\r\n";
        }

        public void Write(string name, string value)
        {

            _writer.Write(Encoding.UTF8.GetBytes("-----------------------------" + _boundary + _newline));
            _writer.Write(Encoding.UTF8.GetBytes(@"Content-Disposition: form-data; name=""" + name + @"""" + _newline));
            _writer.Write(Encoding.UTF8.GetBytes(_newline));
            _writer.Write(Encoding.UTF8.GetBytes(value + _newline));
        }


        public void WriteFile(string name, string filename, string contentType, Stream contents)
        {
            MemoryStream buffer = new MemoryStream();

            Utils.BufferedTransfer(contents, buffer);
            this.WriteFile(name, filename, contentType, buffer.ToArray());
        }
        public void WriteFile(string name, string filename, string contentType, byte[] contents)
        {
            _writer.Write(Encoding.UTF8.GetBytes("-----------------------------" + _boundary + _newline));
            _writer.Write(Encoding.UTF8.GetBytes(@"Content-Disposition: form-data; name=""" + name + @"""; filename=""" + filename + @"""" + _newline));
            _writer.Write(Encoding.UTF8.GetBytes(@"Content-Type: " + contentType + _newline));
            _writer.Write(Encoding.UTF8.GetBytes(_newline));
            _writer.Write(contents);
            _writer.Write(Encoding.UTF8.GetBytes(_newline));
        }

        public void Dispose()
        {
            _writer.Write(Encoding.UTF8.GetBytes("-----------------------------" + _boundary + "--" + _newline));
            _writer.Flush();
        }


    }



}
